package com.motorhome.h5.controller;

import com.motorhome.base.util.JsonUtil;
import com.motorhome.base.util.Result;
import com.motorhome.base.util.StringUtil;
import com.motorhome.h5.domain.*;
import com.motorhome.h5.service.HomeService;
import com.motorhome.h5.service.OpenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: John
 */
@Controller
@RequestMapping("/home")
public class HomeController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private HomeService homeService;

    @Autowired
    private OpenService openService;

    /**
     * 首页，选择城市、时间
     *
     * @return
     */
    @RequestMapping(value = "/index")
    public String index(Model model) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dayFormat = new SimpleDateFormat("MM月dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        model.addAttribute("startFullTime", dateFormat.format(calendar.getTime()));
        model.addAttribute("startDay", dayFormat.format(calendar.getTime()));

        calendar.add(Calendar.DAY_OF_MONTH, 1);
        model.addAttribute("endFullTime", dateFormat.format(calendar.getTime()));
        model.addAttribute("endDay", dayFormat.format(calendar.getTime()));

        return "home/index";
    }

    /**
     * 车辆列表
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request, Model model) {
        String source = (String)request.getAttribute("source");
        if ("web".equals(source)) {
            model.addAttribute("startCityId", (String)request.getSession(true).getAttribute("startCityIdWeb"));
            model.addAttribute("startCityName", (String)request.getSession(true).getAttribute("startCityNameWeb"));
            model.addAttribute("startShopId", (String)request.getSession(true).getAttribute("startShopIdWeb"));
            model.addAttribute("startShopName", (String)request.getSession(true).getAttribute("startShopNameWeb"));
            model.addAttribute("startDate", (String)request.getSession(true).getAttribute("startDateWeb"));
            model.addAttribute("endCityId", (String)request.getSession(true).getAttribute("endCityIdWeb"));
            model.addAttribute("endCityName", (String)request.getSession(true).getAttribute("endCityNameWeb"));
            model.addAttribute("endShopId", (String)request.getSession(true).getAttribute("endShopIdWeb"));
            model.addAttribute("endShopName", (String)request.getSession(true).getAttribute("endShopNameWeb"));
            model.addAttribute("endDate", (String)request.getSession(true).getAttribute("endDateWeb"));
            model.addAttribute("days", (String)request.getSession(true).getAttribute("daysWeb"));

            request.getSession(true).removeAttribute("startCityIdWeb");
            request.getSession(true).removeAttribute("startCityNameWeb");
            request.getSession(true).removeAttribute("startShopIdWeb");
            request.getSession(true).removeAttribute("startShopNameWeb");
            request.getSession(true).removeAttribute("startDateWeb");
            request.getSession(true).removeAttribute("endCityIdWeb");
            request.getSession(true).removeAttribute("endCityNameWeb");
            request.getSession(true).removeAttribute("endShopIdWeb");
            request.getSession(true).removeAttribute("endShopNameWeb");
            request.getSession(true).removeAttribute("endDateWeb");
            request.getSession(true).removeAttribute("daysWeb");

        } else if ("wxindex".equals(source)) {

            String startCityId = (String)request.getAttribute("fromcity");
            String startCityName = (String)request.getAttribute("startCityName");
            String startShopId = (String)request.getAttribute("fromshop");
            String startShopName = (String)request.getAttribute("startShopName");
            String startDate = (String)request.getAttribute("fromdate");
            String endCityId = (String)request.getAttribute("backcity");
            String endCityName = (String)request.getAttribute("endCityName");
            String endShopId = (String)request.getAttribute("backshop");
            String endShopName = (String)request.getAttribute("endShopName");
            String endDate = (String)request.getAttribute("backdate");
            String days = (String)request.getAttribute("days");

            request.getSession(true).setAttribute("fromcity", startCityId);
            request.getSession(true).setAttribute("startCityName", startCityName);
            request.getSession(true).setAttribute("fromshop", startShopId);
            request.getSession(true).setAttribute("startShopName", startShopName);
            request.getSession(true).setAttribute("fromdate", startDate);
            request.getSession(true).setAttribute("backcity", endCityId);
            request.getSession(true).setAttribute("endCityName", endCityName);
            request.getSession(true).setAttribute("backshop", endShopId);
            request.getSession(true).setAttribute("endShopName", endShopName);
            request.getSession(true).setAttribute("backdate", endDate);
            request.getSession(true).setAttribute("days", days);

            model.addAttribute("startCityId", startCityId);
            model.addAttribute("startCityName", "南京");
            model.addAttribute("startShopId", startShopId);
            model.addAttribute("startShopName", "南京秦淮河营地店");
            model.addAttribute("startDate", startDate);
            model.addAttribute("endCityId", endCityId);
            model.addAttribute("endCityName", "南京");
            model.addAttribute("endShopId", endShopId);
            model.addAttribute("endShopName", "南京秦淮河营地店");
            model.addAttribute("endDate", endDate);
            model.addAttribute("days", days);

        } else {

            String startCityId = (String)request.getSession(true).getAttribute("fromcity");
            String startCityName = (String)request.getSession(true).getAttribute("startCityName");
            String startShopId = (String)request.getSession(true).getAttribute("fromshop");
            String startShopName = (String)request.getSession(true).getAttribute("startShopName");
            String startDate = (String)request.getSession(true).getAttribute("fromdate");
            String endCityId = (String)request.getSession(true).getAttribute("backcity");
            String endCityName = (String)request.getSession(true).getAttribute("endCityName");
            String endShopId = (String)request.getSession(true).getAttribute("backshop");
            String endShopName = (String)request.getSession(true).getAttribute("endShopName");
            String endDate = (String)request.getSession(true).getAttribute("backdate");
            String days = (String)request.getSession(true).getAttribute("days");

            model.addAttribute("startCityId", startCityId);
            model.addAttribute("startCityName", "南京");
            model.addAttribute("startShopId", startShopId);
            model.addAttribute("startShopName", "南京秦淮河营地店");
            model.addAttribute("startDate", startDate);
            model.addAttribute("endCityId", endCityId);
            model.addAttribute("endCityName", "南京");
            model.addAttribute("endShopId", endShopId);
            model.addAttribute("endShopName", "南京秦淮河营地店");
            model.addAttribute("endDate", endDate);
            model.addAttribute("days", days);
        }

        List<Car> carList = homeService.getAllCarList(model.asMap());

        model.addAttribute("carList", carList);

        return "home/list2";
    }

    /**
     * 订单详情
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/order")
    public String order(HttpServletRequest request, Model model) {

        User loginUser = (User)request.getAttribute("loginUser");

        String startCityId = (String)request.getAttribute("startCityId");
        String startCityName = (String)request.getAttribute("startCityName");
        String startShopId = (String)request.getAttribute("startShopId");
        String startShopName = (String)request.getAttribute("startShopName");
        String startDate = (String)request.getAttribute("startDate");
        String endCityId = (String)request.getAttribute("endCityId");
        String endCityName = (String)request.getAttribute("endCityName");
        String endShopId = (String)request.getAttribute("endShopId");
        String endShopName = (String)request.getAttribute("endShopName");
        String endDate = (String)request.getAttribute("endDate");
        String carId = (String)request.getAttribute("carId");
        String carName = (String)request.getAttribute("carName");
        String carDescription = (String)request.getAttribute("carDescription");
        String picUrl = (String)request.getAttribute("picUrl");
        String price = (String)request.getAttribute("price"); //单价
        String days = (String)request.getAttribute("days"); //天数

        model.addAttribute("startCityId", startCityId);
        model.addAttribute("startCityName", startCityName);
        model.addAttribute("startShopId", startShopId);
        model.addAttribute("startShopName", startShopName);
        model.addAttribute("startTime", startDate.substring(9, 14));
        model.addAttribute("endCityId", endCityId);
        model.addAttribute("endCityName", endCityName);
        model.addAttribute("endShopId", endShopId);
        model.addAttribute("endShopName", endShopName);
        model.addAttribute("endDate", endDate);
        model.addAttribute("carId", carId);
        model.addAttribute("carName", carName);
        model.addAttribute("carDescription", carDescription);
        model.addAttribute("price", price);
        model.addAttribute("days", days);
        model.addAttribute("picUrl", picUrl);

        //时间格式化
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            SimpleDateFormat dateFormat2 = new SimpleDateFormat("MM月dd日");
            SimpleDateFormat dateFormat3 = new SimpleDateFormat("HH:mm");
            Date startD = dateFormat.parse(startDate);
            Date endD = dateFormat.parse(endDate);
            model.addAttribute("startDate2", dateFormat2.format(startD));
            model.addAttribute("startTime", dateFormat3.format(startD));
            model.addAttribute("endDate2", dateFormat2.format(endD));
            model.addAttribute("endTime", dateFormat3.format(endD));
        } catch (Exception e) {
        }

        //查询价格折扣
        Price dbPrice = homeService.getPriceByCarId(Long.parseLong(carId));

        Car car = homeService.getCarById(Long.parseLong(carId));
        model.addAttribute("car", car);

        //1、计算租车期间的周末天数
        int weekendDays = 0;
        Calendar startDateCal = Calendar.getInstance();
        Calendar endDateCal = Calendar.getInstance();
        try {
            startDateCal.setTime(dateFormat.parse(startDate));
            endDateCal.setTime(dateFormat.parse(endDate));
        } catch (ParseException e) {
        }
        while (startDateCal.before(endDateCal)) {
            int weekend = startDateCal.get(Calendar.DAY_OF_WEEK);
            if (weekend == Calendar.SUNDAY || weekend == Calendar.SATURDAY) {
                weekendDays++;
            }
            startDateCal.add(Calendar.DAY_OF_MONTH, 1);
        }

        //2、日常总价
        int totalDays = Integer.parseInt(days);
        int normalDays = totalDays - weekendDays;
        float total = normalDays * dbPrice.getPrice();
        String totalSnapshot = "日常天数" + normalDays + "*日常价" + dbPrice.getPrice();
        model.addAttribute("totalDays", totalDays);
        model.addAttribute("normalDays", normalDays);
        model.addAttribute("dayPrice", dbPrice.getPrice());
        model.addAttribute("dayTotalPrice", total);

        //3、周末溢价
        if (weekendDays > 0) {
            Float weekendTotalPrice = weekendDays * (dbPrice.getPrice() + dbPrice.getRateWeekend());
            total = total + weekendTotalPrice;
            totalSnapshot = totalSnapshot + " + (周末天数" + weekendDays + "*(日常价" +dbPrice.getPrice()+"+周末溢价" + dbPrice.getRateWeekend()+"))";
            model.addAttribute("weekendDays", weekendDays);
            model.addAttribute("weekendDayPrice", dbPrice.getPrice() + dbPrice.getRateWeekend());
            model.addAttribute("weekendTotalPrice", weekendTotalPrice);
        }

        //4、长租折扣
        if (totalDays >= dbPrice.getDay1() && totalDays < dbPrice.getDay2()) {
            float longTimeReduce = Math.round(total - (total * dbPrice.getRate1()));
            model.addAttribute("longTimeReduce", longTimeReduce);
            total = total * dbPrice.getRate1();
            totalSnapshot = "(" + totalSnapshot + ")*长租折扣" + dbPrice.getRate1();
        } else if (totalDays >= dbPrice.getDay2() && totalDays < dbPrice.getDay3()) {
            float longTimeReduce = Math.round(total - (total * dbPrice.getRate2()));
            model.addAttribute("longTimeReduce", longTimeReduce);
            total = total * dbPrice.getRate2();
            totalSnapshot = "(" + totalSnapshot + ")*长租折扣" + dbPrice.getRate2();
        } else if (totalDays >= dbPrice.getDay3()) {
            float longTimeReduce = Math.round(total - (total * dbPrice.getRate3()));
            model.addAttribute("longTimeReduce", longTimeReduce);
            total = total * dbPrice.getRate3();
            totalSnapshot = "(" + totalSnapshot + ")*长租折扣" + dbPrice.getRate3();
        }

        //5、会员折扣
        if (loginUser.getVipId() != null && loginUser.getVipId() > 0) {
            float vipReduce = Math.round(total - (total * loginUser.getVipRate()));
            model.addAttribute("vipReduce", vipReduce);
            total = total * loginUser.getVipRate();
            totalSnapshot = "(" + totalSnapshot + ")*" + loginUser.getVipName() + loginUser.getVipRate();
        }

        //6、车辆保险
        Float insurance = car.getInsurance();
        if (insurance != null && insurance != 0) {
            Float totalInsurance = totalDays * insurance;
            model.addAttribute("insurance", insurance.intValue());
            model.addAttribute("totalInsurance", totalInsurance);
            total = Math.round(total + totalInsurance);
            totalSnapshot = totalSnapshot + "+(总天数" + totalDays + "*日保险" + insurance + ")";
        }

        model.addAttribute("total", total);
        model.addAttribute("totalSnapshot", totalSnapshot);

        //查询优惠券列表
        String couponResultJson = openService.getCoupnSendPagedV2(loginUser.getCardId());
        List<OpenCoupon> couponList = null;
        if (StringUtil.isNotBlank(couponResultJson)) {
            OpenCouponResult couponResult = JsonUtil.fromJson(couponResultJson, OpenCouponResult.class);
            if (couponResult != null && couponResult.getStatus() == 0) {
                couponList = couponResult.getCouponList();
            }
        }
        model.addAttribute("couponList", couponList);

        return "home/order2";
    }

    /**
     * 费用明细
     *
     * @return
     */
    @RequestMapping(value = "/fee")
    public String fee(HttpServletRequest request, Model model) {
        String normalDays = request.getParameter("normalDays");
        String weekendDays = request.getParameter("weekendDays");
        String dayTotalPrice = request.getParameter("dayTotalPrice");
        String weekendTotalPrice = request.getParameter("weekendTotalPrice");
        String longTimeReduce = request.getParameter("longTimeReduce");
        String vipReduce = request.getParameter("vipReduce");
        String insurance = request.getParameter("insurance");
        String total = request.getParameter("total");

        model.addAttribute("normalDays", StringUtil.isBlank(normalDays) ? 0 : normalDays);
        model.addAttribute("dayTotalPrice", StringUtil.isBlank(dayTotalPrice) ? 0 : dayTotalPrice);
        model.addAttribute("weekendDays", StringUtil.isBlank(weekendDays) ? 0 : weekendDays);
        model.addAttribute("weekendTotalPrice", StringUtil.isBlank(weekendTotalPrice) ? 0 : weekendTotalPrice);
        model.addAttribute("longTimeReduce", StringUtil.isBlank(longTimeReduce) ? 0 : Float.parseFloat(longTimeReduce));
        model.addAttribute("vipReduce", StringUtil.isBlank(vipReduce) ? 0 : Float.parseFloat(vipReduce));
        model.addAttribute("insurance", StringUtil.isBlank(insurance) ? 0 : insurance);
        model.addAttribute("total", StringUtil.isBlank(total) ? 0 : total);

        return "home/fee";
    }

    /**
     * 提交订单
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/submitOrder", method = RequestMethod.POST)
    public @ResponseBody Result submitOrder(HttpServletRequest request, Model model) {
        User loginUser = (User)request.getAttribute("loginUser");
        String startCityId = (String)request.getAttribute("startCityId");
        String startCityName = (String)request.getAttribute("startCityName");
        String startShopId = (String)request.getAttribute("startShopId");
        String startShopName = (String)request.getAttribute("startShopName");
        String startDate = (String)request.getAttribute("startDate");
        String endCityId = (String)request.getAttribute("endCityId");
        String endCityName = (String)request.getAttribute("endCityName");
        String endShopId = (String)request.getAttribute("endShopId");
        String endShopName = (String)request.getAttribute("endShopName");
        String endDate = (String)request.getAttribute("endDate");
        String carId = (String)request.getAttribute("carId");
        String carName = (String)request.getAttribute("carName");
        String carDescription = (String)request.getAttribute("carDescription");
        String price = (String)request.getAttribute("price"); //单价
        String days = (String)request.getAttribute("days"); //天数
        String total = (String)request.getAttribute("total"); //总计
        String totalSnapshot = (String)request.getAttribute("totalSnapshot"); //总计快照

        Result result = homeService.insertOrder(request, loginUser, startCityId, startCityName, startShopId, startShopName,
                startDate, endCityId, endCityName, endShopId, endShopName, endDate, carId, carName, carDescription,
                price, days, total, totalSnapshot);

        return result;
    }

    /**
     * 网站跳转查询
     *
     * @return
     */
    @RequestMapping(value = "/webIndex")
    public void webIndex(HttpServletRequest request, HttpServletResponse response, Model model) {

//        String startCityId = request.getParameter("fromcity");
//        String startCityName = request.getParameter("startCityName");
//        String startShopId = request.getParameter("fromshop");
//        String startShopName = request.getParameter("startShopName");
//        String endCityId = request.getParameter("backcity");
//        String endCityName = request.getParameter("endCityName");
//        String endShopId = request.getParameter("backshop");
//        String endShopName = request.getParameter("endShopName");

        String startDate = request.getParameter("fromdate");
        String endDate = request.getParameter("backdate");
        String days = request.getParameter("days");

        logger.info("fromdate=" + startDate + ",backdate=" + endDate + ",days=" + days);

        //构建表单信息
        StringBuffer form = new StringBuffer();
        form.append("<!doctype html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
        form.append("<title>正在进入应用</title></head><body>");
        form.append("<form id=\"jumpForm\" name=\"jumpForm\" action=\"" + request.getContextPath() + "/h5/home/list" + "\" method=\"post\" enctype=\"application/x-www-form-urlencoded\">");
        form.append("<input name=\"fromcity\" type=\"hidden\" value=\"1\"/>");
        form.append("<input name=\"startCityName\" type=\"hidden\" value=\"南京\"/>");
        form.append("<input name=\"fromshop\" type=\"hidden\" value=\"1\"/>");
        form.append("<input name=\"startShopName\" type=\"hidden\" value=\"南京秦淮河营地店\"/>");
        form.append("<input name=\"backcity\" type=\"hidden\" value=\"1\"/>");
        form.append("<input name=\"endCityName\" type=\"hidden\" value=\"南京\"/>");
        form.append("<input name=\"backshop\" type=\"hidden\" value=\"1\"/>");
        form.append("<input name=\"endShopName\" type=\"hidden\" value=\"南京秦淮河营地店\"/>");
        form.append("<input name=\"fromdate\" type=\"hidden\" value=\"" + startDate + "\"/>");
        form.append("<input name=\"backdate\" type=\"hidden\" value=\"" + endDate + "\"/>");
        form.append("<input name=\"days\" type=\"hidden\" value=\"" + days + "\"/>");
        form.append("</form>");
        form.append("<script>document.forms['jumpForm'].submit();</script>");
        form.append("</body></html>");

        //提交请求
        try {
            response.getWriter().write(form.toString());
        } catch (IOException e) {
            logger.error("网站跳转异常", e);
        }
    }

    /**
     * 微信公众号支付
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/tenpay")
    public String tenpay(HttpServletRequest request, Model model) {
        homeService.tenPay(request, model);
        return "home/tenpay";
    }

    /**
     * 微信支付结果异步通知
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/tenpay-notify", method = RequestMethod.POST)
    public @ResponseBody String tenpayNotify(HttpServletRequest request, @RequestBody String resultXml) {
        return homeService.tenpayNotify(request, resultXml);
    }

}
